package com.xmh.code.util;

import io.github.resilience4j.ratelimiter.RateLimiter;
import io.github.resilience4j.ratelimiter.RateLimiterConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.function.Supplier;

@Slf4j
public class ResultUtil {

    private ResultUtil() {
    }

    private static final RateLimiter rateLimiter;

    static {
        rateLimiter = RateLimiter.of("myRateLimiter", RateLimiterConfig.custom()
                .limitForPeriod(1)  // 每秒最大请求数
                .limitRefreshPeriod(Duration.ofSeconds(1))  // 刷新时间窗口
                .timeoutDuration(Duration.ofMillis(500))  // 请求超时
                .build());
    }

    public static <T> Mono<ResponseEntity<T>> rateLimiterHandle(Object data, Supplier<T> runnable) {
        return Mono.just(rateLimiter.acquirePermission())
                .flatMap(permissionGranted -> {
                    if (Boolean.TRUE.equals(permissionGranted)) {
                        return Mono.just(new ResponseEntity<>(runnable.get(), HttpStatus.OK));
                    } else {
                        log.error("{} Too Many Requests", data);
                        return Mono.just(new ResponseEntity<>(HttpStatus.TOO_MANY_REQUESTS));
                    }
                });
    }
}
